""" 
    解压 alp -> 文件夹
    打包 文件夹 -> alp
"""

import os
import zipfile
import fnmatch
from pathlib import Path

LOCAL_PATH = Path(__file__).parent


def traverse_files(path, match_suffix=None):
    """
    遍历指定路径下的所有文件夹和文件，根据后缀名过滤文件。
    """
    matched_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if match_suffix is None or fnmatch.fnmatch(file, f"*{match_suffix}"):
                matched_files.append(os.path.join(root, file))
    return matched_files


def unzip_file(zip_path, output_folder):
    """
    解压ZIP文件到指定的输出文件夹。
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    with zipfile.ZipFile(zip_path, "r") as zip_ref:
        zip_ref.extractall(output_folder)


def pack_files_to_alp(folder_path, output_alp_path):
    """
    将文件夹下的所有文件打包为对应的.alp压缩包。
    """
    output_dir = Path(output_alp_path).parent
    if not output_dir.exists():
        output_dir.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(output_alp_path, "w") as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                relative_path = os.path.relpath(file_path, folder_path)
                zipf.write(file_path, arcname=relative_path)


def traverse_folders_one_level(path):
    """
    遍历指定路径下一层的所有文件夹。
    """
    subfolders = []
    entries = os.listdir(path)
    for entry in entries:
        full_path = Path(path).joinpath(entry)
        if full_path.is_dir():
            subfolders.append(full_path)
    return subfolders


def process_files(action, path, output_path=None, match_suffix=None):
    """
    处理文件，支持解压和压缩。
    """
    if action == "unzip":
        for file_path in traverse_files(path, match_suffix):
            filename_without_suffix = Path(file_path).stem
            unzip_file(file_path, os.path.join(output_path, filename_without_suffix))
    elif action == "zip":
        if output_path is None:
            output_path = LOCAL_PATH
        for folder in traverse_folders_one_level(path):
            output_alp_path = os.path.join(output_path, folder.name + ".alp")
            pack_files_to_alp(folder, output_alp_path)


def process_folders(action, path):
    """
    处理文件夹，支持遍历。
    """
    if action == "list":
        return traverse_folders_one_level(path)


def main_process(action, path, output_path=None, match_suffix=None):
    """
    主处理函数，根据action参数决定执行哪个操作。
    """
    if action in ["unzip", "zip"]:
        process_files(action, path, output_path, match_suffix)
    elif action == "list":
        return process_folders(action, path)


# 使用示例
if __name__ == "__main__":
    # 解压res目录下所有.alp文件到output目录
    main_process("unzip", "lua-alp", "output", ".alp")

    # 打包output目录下每个文件夹为对应的.alp文件
    # main_process("zip", "output", "res")

    # 遍历output目录下一层的所有文件夹
    # folders = main_process("list", "output")
    # print(folders)
